var Level = require('Level');
var Game = cc.Class({
    extends: cc.Component,
    //self : this,
    properties: {
        //UI 
        rightArea : {
            default : null,
            type : cc.Node
        },
        controlArea : {
            default : null,
            type : cc.Node
        },
        gameArea : {
            default : null,
            type : cc.Node
        },
        infoArea : {
            default : null,
            type : cc.Node
        },
        pauseArea : {
            default : null,
            type : cc.Node
        },
        physicsCube : {
            default : [],
            type : cc.Prefab,
        },
        speed : {
            default : 300,
        },
        step : {
            default : 2,
        }
    },
    
    // use this for initialization
    onLoad: function () {
        Game.instance = this;
        var self = this;
        // 全局变量
        // 初始化资源
        this.cubeUI = new Array(this.physicsCube.length);
        this.initTexture();
        this.pauseBtn = this.controlArea.getChildByName('pauseBtn');
        this.pauseBtn.active = true;
        this.life = 9;
        //边界坐标用于判断节点出局
        this.bottomBorder = this.gameArea.y-this.gameArea.height/2;
        this.leftBorder = this.gameArea.x-this.gameArea.width/2;
        this.rightBorder = this.gameArea.x+this.gameArea.width/2;
        this.wallDownNode = this.gameArea.getChildByName('Wall_down');
        // 区域获取当前节点和下一个节点
        this.curNode = this.rightArea.getChildByName('curNode');
        this.nextNode = this.rightArea.getChildByName('nextNode'); 
        this.curNodeSprite = this.curNode.getComponent(cc.Sprite);
        this.nextNodeSprite = this.nextNode.getComponent(cc.Sprite);
        // 初始化展示数字标签
        this.lifeNode = this.infoArea.getChildByName('life');
        this.highMeterNode = this.infoArea.getChildByName('highMeter');
        this.highMeter = 0;
        this.highMeterNode.getComponent(cc.Label).string = (this.highMeter+'m');
        this.highMeterLineNode = this.gameArea.getChildByName('highMeterLine');
        // 展示当前节点和下一节点
        this.curID = Math.floor(Math.random(0,1)*this.physicsCube.length);
        this.nextID = Math.floor(Math.random(0,1)*this.physicsCube.length);
        this.maxHeight = 0;
        // 物理组件
        this.firstCube = true;
        this.physicsControlCube = null;
        this.generateCube();
       
        // UI
        this.accDelta = 0; //累积位移
        this.lastDelta = 0; //上一次位移
        this.lifeNode.getComponent(cc.Label).string = this.life;
        // Handler
        this.gameArea.on(cc.Node.EventType.TOUCH_MOVE,function(event){
            var x = event.getDelta().x;
            if(x === 0){
                return;
            }
            var cube = self.physicsControlCube.getComponent('Cube');
            //console.log("event.delta:"+event.getDelta().x+","+event.getDelta()+"; getLoc:"+event.getLocation().x+","+event.getLocation().y+"; getstart:"+event.getStartLocation().x+","+event.getStartLocation().y);
            //滑动方向改变，重新开始累积位移
            if((self.lastDelta>0 && x<0) || (self.lastDelta<0 && x>0)){
                self.accDelta = 0;
            }
            //判断累积位移是否已经从一个domain到了下一个domain
            //domain之间的距离为step
            var newDomain = Math.floor((self.accDelta+x)/self.step);
            var lastDomain = Math.floor(self.accDelta/self.step);
            if(Math.abs(newDomain)>Math.abs(lastDomain)){
                var delta = (Math.abs(newDomain)-Math.abs(lastDomain))*self.step;
                if(x<0){
                    cube.onLeft(delta);
                }
                if(x>0){
                    cube.onRight(delta);
                }
            }
            self.accDelta = self.accDelta + x;
            self.lastDelta = x;
            
        },this);
        this.gameArea.on(cc.Node.EventType.TOUCH_END,function(event){
            //
            if(self.accDelta === 0){
                var cube = self.physicsControlCube.getComponent('Cube');
                cube.onChangeDirection();
            }
            self.accDelta = 0;
            self.lastDelta = 0;
        },this);
    },
    initTexture : function(){
        
        for (var i=0;i<this.physicsCube.length;i++){
            this.cubeUI[i] = cc.textureCache.addImage(cc.url.raw("resources/My/cube"+i+".png"));
        }
        this.pauseBtnTexture = cc.textureCache.addImage(cc.url.raw("resources/My/pauseBtn.png"));
        this.playBtnTexture = cc.textureCache.addImage(cc.url.raw("resources/My/playBtn.png"));
    },

    // called every frame, uncomment this function to activate update callback
    update: function (dt) {
        var cube = this.physicsControlCube.getComponent('Cube');
        if(cube.firstContract){
            this.deta += dt;
            if(this.deta < 2)return;
            this.deta = 0;
            this.generateCube();
        }
    },
    generateCube:function(){
        // 绘画右侧区域
        this.curNodeSprite.spriteFrame = new cc.SpriteFrame(this.cubeUI[this.curID]);
        this.nextNodeSprite.spriteFrame = new cc.SpriteFrame(this.cubeUI[this.nextID]);
        // 产生主游戏方块逻辑
        var cube= cc.instantiate(this.physicsCube[this.curID]);
        cube.x = 0;
        cube.y = this.gameArea.height/2 - cube.width - this.gameArea.y;
        this.gameArea.addChild(cube);
        this.physicsControlCube = cube;
        // 产生下一个方块随机数，并将Next替换cur
        this.curID = this.nextID;
        this.nextID = Math.floor(Math.random(0,1)*this.physicsCube.length);
        
        return cube;
    },
    endGame:function(){
        if(cc.director.isPaused(this)){
            cc.director.resume(this);
            this.pauseBtn.active = true;
        }
        cc.director.loadScene('Menu');
    },
    pauseGame:function(){
        if(cc.director.isPaused(this)){
            cc.director.resume(this);
            this.pauseBtn.active = true;
               //getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(this.pauseBtnTexture);
            this.pauseArea.active = false;
        }else{
            cc.director.pause(this);
            //this.pauseBtn.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(this.playBtnTexture);
            this.pauseBtn.active =false;
            this.pauseArea.active = true;
        }
    },
    refreshGame:function(){
        if(cc.director.isPaused(this)){
            cc.director.resume(this);
            this.pauseBtn.active = true;
        }
        cc.director.loadScene('Game');
    },
    store:function(){
        cc.director.loadScene('Store');
    },
    moveBg:function(distance){
        this.gameArea.runAction(cc.moveBy(0,cc.p(0,-distance)));
        /*console.log("before "+this.gameArea.children[3].y);
        for(var i=0;i<this.gameArea.childrenCount;i++){
            var chd = this.gameArea.children[i];
            chd.y = chd.y+distance;
        }
        console.log("after "+this.gameArea.children[3].y);*/
    },
    subLife:function(life){
        this.life -= life;
        this.lifeNode.getComponent(cc.Label).string = this.life;
    },
    updateHighMeter:function(meter){
        var oldMeter = this.highMeter;
        
        this.highMeter = meter;
        this.highMeterNode.getComponent(cc.Label).string = (this.highMeter+'米');
        this.highMeterLineNode.runAction(cc.moveBy(0.5,cc.p(0,meter-oldMeter)));
    }
});
module.exports = Game;
